<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>

    <body>
        <canvas id="myCanvas" width="400px" height="400px" style="border:1px solid #000000;">
        </canvas>
        <button onclick="addDot()">添加结点</button>
    </body>


</html>


<script>
    //存放点坐标的数组 如 dots[0][0],dots[0][1]分别为第一个点的x和y
    var dots = [];
    // 定义存放即将被连线点的坐标 drawpoint[0],drawpoint[1]分别存放第一个点的x和y drawpoint[2]drawpoint[3]分别存放第二个点的x和y
    var drawpoint = [];

    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var color = "red";
    // di为dots的下标
    var di = 0;
    // 标志是点击的第一个点还是第二个点
    var flag = 0;

    window.onload = function() {
        // 监听点击事件
        c.addEventListener("mouseup", drawline);
    }

    function drawline(event) {
        // 鼠标当前的位置
        var x = event.clientX - c.getBoundingClientRect().left;
        var y = event.clientY - c.getBoundingClientRect().top;

        for (var i = 0; i < dots.length; i++) {
            ctx.beginPath();
            // ctx.arc(dots[i][0],dots[i][1],10,0,360);
            // 通过距离计算判断当前点是否在圆内
            if (((x - dots[i][0]) * (x - dots[i][0]) + (y - dots[i][1]) * (y - dots[i][1])) < 100) {
                if (flag % 2 == 0) {
                    drawpoint[0] = dots[i][0];
                    drawpoint[1] = dots[i][1];

                } else {
                    drawpoint[2] = dots[i][0];
                    drawpoint[3] = dots[i][1];
                    ctx.strokeStyle = "#0000ff";
                    ctx.moveTo(drawpoint[0], drawpoint[1]);
                    ctx.lineTo(drawpoint[2], drawpoint[3]);
                    ctx.stroke();
                }

                flag = flag + 1;
            }
        }

    }

    function addDot() {
        var point = [Math.floor(Math.random() * 390), Math.floor(Math.random() * 390)];
        dots[di] = point;
        di = di + 1;
        createDot(point[0], point[1]);
    }

    function createDot(x, y) {
        ctx.fillStyle = '#000000' //字体颜色

        ctx.beginPath(); // 开始画图
        ctx.arc(x, y, 10, 0, 360); //图形位置与形状
        ctx.fillStyle = color; //图形填充颜色
        ctx.fill(); //画实心圆
        ctx.closePath();
    }
</script>

